import request from '@/utils/ApiClient';
import WKSDK, {
  Channel,
  ChannelInfo,
  ChannelTypeGroup,
  ChannelTypePerson,
} from 'wukongimjssdk';

export default class ImDataSource {
  constructor() {
    this.setChannelInfoCallback();
  }

  private setChannelInfoCallback() {
    WKSDK.shared().config.provider.channelInfoCallback = async function (
      channel: Channel
    ): Promise<ChannelInfo> {
      let channelInfo = new ChannelInfo(),
        isUsers = channel.channelType === ChannelTypePerson;
      const resp = await request.get(
        `channels/${channel.channelID}/${channel.channelType}`
      );

      const data = resp;

      channelInfo.channel = new Channel(
        data.channel.channel_id,
        data.channel.channel_type
      );
      channelInfo.title = data.name;
      channelInfo.mute = data.mute === 1;
      channelInfo.top = data.stick === 1;
      channelInfo.online = data.online === 1;
      channelInfo.lastOffline = data.last_offline;
      channelInfo.logo = data.logo;
      if (!channelInfo.logo || channelInfo.logo === '') {
        if (channel.channelType === ChannelTypePerson) {
          channelInfo.logo = `users/${channel.channelID}/avatar`;
        } else if (channel.channelType === ChannelTypeGroup) {
          channelInfo.logo = `groups/${channel.channelID}/avatar`;
        }
      }

      channelInfo.orgData = data.extra || {};
      channelInfo.orgData.remark = data.remark ?? '';
      channelInfo.orgData.displayName =
        data.remark && data.remark !== '' ? data.remark : channelInfo.title;

      channelInfo.orgData.receipt = data.receipt;
      channelInfo.orgData.robot = data.robot;
      channelInfo.orgData.status = data.status;
      channelInfo.orgData.follow = data.follow;
      channelInfo.orgData.category = data.category;
      channelInfo.orgData.be_deleted = data.be_deleted;
      channelInfo.orgData.be_blacklist = data.be_blacklist;
      channelInfo.orgData.notice = data.notice;

      if (channel.channelType === ChannelTypePerson) {
        channelInfo.orgData.shortNo = data.extra.short_no ?? '';
      } else if (channel.channelType === ChannelTypeGroup) {
        channelInfo.orgData.forbidden = data.forbidden;
        channelInfo.orgData.invite = data.invite;
        channelInfo.orgData.forbiddenAddFriend =
          data.extra.forbidden_add_friend;
        channelInfo.orgData.save = data.save;
      }
      if (data.category === 'system' || data.category === 'customerService') {
        // 官方账号
        channelInfo.orgData.identityIcon = './identity_icon/official.png';
        channelInfo.orgData.identitySize = { width: '18px', height: '18px' };
      } else if (data.category === 'visitor') {
        channelInfo.orgData.identityIcon = './identity_icon/visitor.png';
        channelInfo.orgData.identitySize = { width: '48px', height: '24px' };
      }

      return channelInfo;
    };
  }
}
